//
//  ViewController.m
//  05-聊天室
//
//  Created by J on 15/11/8.
//  Copyright © 2015年 JZJ. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<NSStreamDelegate>{
    NSInputStream * _inputStream;//输入流
    NSOutputStream * _outputStream;//对应输出流
    
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //1.建立连接
    NSString * host=@"127.0.0.1";
    int port = 12345;
    //定义C 语言输入输出流
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    
    
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &readStream, &writeStream);
    
    
//    把C语言输入输出流转换成OC对象
    _inputStream = (__bridge NSInputStream *)(readStream);//readStream让它自动提示补全
    
    _outputStream = (__bridge NSOutputStream *)(writeStream);

    //设置代理
    _inputStream.delegate = self;
    
    _outputStream.delegate=self;
    
    
    //把输入输出流添加到主运行循环 不添加主运行循环 代理可能不工作
    [_inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [_outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

    //打开输入输出流
    [_inputStream open];
    [_outputStream open];
    
    
    //2.收发数据
    
    


}

#pragma mark --NSStreamDelegate

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
    
    NSLog(@"%@",aStream);
    
//    NSStreamEventOpenCompleted = 1UL << 0,  //输入输出流打开完成
//    NSStreamEventHasBytesAvailable = 1UL << 1,//有字节可读
//    NSStreamEventHasSpaceAvailable = 1UL << 2,//可以发送字节
//    NSStreamEventErrorOccurred = 1UL << 3,//连接出现错误
//    NSStreamEventEndEncountered = 1UL << 4//连接结束
    
    
    switch (eventCode) {
        case NSStreamEventOpenCompleted:
            
            NSLog(@"NSStreamEventOpenCompleted");
            
            break;
            
        case NSStreamEventHasBytesAvailable:
            
            NSLog(@"NSStreamEventHasBytesAvailable");

        break;
    
        case NSStreamEventHasSpaceAvailable:
            
            NSLog(@"NSStreamEventHasSpaceAvailable");

            break;
            
        case NSStreamEventErrorOccurred:
            
            NSLog(@"NSStreamEventErrorOccurred");

            break;
            
        case NSStreamEventEndEncountered:
            
            NSLog(@"NSStreamEventEndEncountered");

            break;
            
            
        default:
            
            break;
            
    }

    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
